/*
 * 
 */
package org.zxstudio.encrypt;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.zxstudio.encrypt.task.EncryptListener;
import org.zxstudio.encrypt.task.TaskController;
import org.zxstudio.encrypt.tree.FileTreeTraverser;
import org.zxstudio.encrypt.utils.FileComparator;
import org.zxstudio.encrypt.utils.RLog;
import org.zxstudio.encrypt.utils.SDUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;

public class TwFileExplorerActivity extends Activity implements
		OnClickListener, EncryptListener.CallBack {

	private static final String TAG = "TwFileExplorerActivity";
	private static final boolean DEBUG = true;

	private FileChildAdapter mChildAdapter;
	private FileParentAdapter mParentAdapter;
	private List<File> mChildFiles = new ArrayList<File>();
	private List<File> mParentFiles = new ArrayList<File>();

	private File mCurrentPath;

	private ListView mParentList;
	private ListView mChildList;
	private GridView mGridView;
	private View mOptionView;
	private Button mEncryptBtn;
	private Button mCancelBtn;
	
	private TaskController  mTc;
	private ProgressDialog  mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.twi_files_list);
		initRes();
	}

	/**
	 * 
	 */
	private void initRes() {
		mParentList = (ListView) findViewById(R.id.parent);
		mChildList = (ListView) findViewById(R.id.child);
		mChildList.setOnItemClickListener(mChildItemClickListener);
		mChildAdapter = new FileChildAdapter(this, mChildFiles);
		mChildAdapter.setViewMode(FileBaseAdapter.VIEWMODE_LIST);
		mChildAdapter.registerItemSelectListener(onItemSelectedListener);
		mChildList.setAdapter(mChildAdapter);
		mParentAdapter = new FileParentAdapter(this, mParentFiles);
		mParentAdapter.setViewMode(FileBaseAdapter.VIEWMODE_LIST);
		mParentList.setAdapter(mParentAdapter);
		mParentList.setOnItemClickListener(mParentItemClickListener);
		mOptionView = findViewById(R.id.option_view);
		mEncryptBtn = (Button) findViewById(R.id.encrypt);
		mEncryptBtn.setOnClickListener(this);
		mCancelBtn = (Button) findViewById(R.id.cancel);
		mCancelBtn.setOnClickListener(this);
		if (SDUtils.isAvailableCurrentSD()) {
			openChildFile(SDUtils.getSdRootPath(), true);
		} else {
			Toast.makeText(this, R.string.no_sdcard, Toast.LENGTH_LONG).show();
		}
		
		mTc = TaskController.getInstance(this);
		mTc.registerEncryptListener(this);
	}

	private OnItemClickListener mChildItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View view, int position,
				long arg3) {

			File file = mChildFiles.get(position);
			if (file.isDirectory()) {
				openChildFile(file, true);
			}
		}

	};

	private OnItemClickListener mParentItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			openParentFile(position);
		}

	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mChildAdapter.unregisterItemSelectListener();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {

		if (mParentFiles.size() == 1) {
			// finish();
			super.onBackPressed();
			return;
		} else {
			// 返回上一级目录
			openUpFiles();
			return;
		}
	}

	// 返回上一级目录
	private void openUpFiles() {
		openParentFile(mParentFiles.size() - 2);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	/**
	 * 
	 * @param f
	 * @param flags
	 */
	private void openChildFile(File f, boolean flags) {
		mCurrentPath = f;
		File[] files = f.listFiles();
		Arrays.sort(files, new FileComparator());
		mChildFiles.clear();
		for (File file : files) {
			if (!file.isHidden() && file.canWrite()) {
				mChildFiles.add(file);
			}
		
		}
		if (flags) {
			mParentFiles.add(mCurrentPath);
			mParentAdapter.notifyDataSetChanged();
		}
		mChildAdapter.notifyDataSourceChanged();
	}

	private void refreshChildFiles() {
		if (mChildFiles != null && mChildFiles.size() > 0) {
			File[] files = mChildFiles.get(0).getParentFile().listFiles();
			Arrays.sort(files, new FileComparator());
			mChildFiles.clear();
			for (File file : files) {
				if (!file.isHidden()) {
					mChildFiles.add(file);
				}
			
			}
		}

	}

	private void openParentFile(int position) {
		if (DEBUG) {
			Log.v(TAG, "openParentFile:" + position);
		}
		if (position < 0 || position > mParentFiles.size() - 1) {
			return;
		}
		File file = mParentFiles.get(position);

		if (DEBUG) {
			Log.v(TAG, "parent files size is :" + mParentFiles.size());
		}
		int size = mParentFiles.size();
		for (int i = size - 1; (i < size) && (i != position); i--) {
			if (DEBUG) {
				Log.v(TAG, "remove parent files index is " + i);
			}
			mParentFiles.remove(i);
		}

		openChildFile(file, false);
		mParentAdapter.notifyDataSetChanged();
	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			RLog.v(TAG, "加密完成,刷新UI");
			if (mChildAdapter != null) {
				refreshChildFiles();
				if (mProgressDialog != null) {
					mProgressDialog.dismiss();
				}
				
				mChildAdapter.notifyDataSourceChanged();
			}
		}

	};
	FileChildAdapter.onItemSelectedListener onItemSelectedListener = new FileChildAdapter.onItemSelectedListener() {

		@Override
		public void noItemSelected() {
			if (mOptionView.getVisibility() != View.GONE) {
				Animation ani = AnimationUtils.loadAnimation(
						TwFileExplorerActivity.this, R.anim.btn_translate_g);
				mOptionView.startAnimation(ani);
				mOptionView.setVisibility(View.GONE);
			}
		}

		@Override
		public void hasItemSelected() {
			if (mOptionView.getVisibility() == View.GONE) {
				Animation ani = AnimationUtils.loadAnimation(
						TwFileExplorerActivity.this, R.anim.btn_translate_v);
				mOptionView.startAnimation(ani);
				mOptionView.setVisibility(View.VISIBLE);
			}

		}
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.encrypt:
			List<File> encryptList = mChildAdapter.getSelectedList();
			/*TaskController tc = TaskController
					.getInstance(TwFileExplorerActivity.this);
			tc.registerEncryptListener(this);*/
	//		mTc.encryptFolder(encryptList);
			//mTc.encryptImage(encryptList);
			mTc.encrypt(encryptList);
			mProgressDialog = ProgressDialog.show(
					TwFileExplorerActivity.this,
					"",
					getResources().getString(
							R.string.encrypt_file));
			break;
		case R.id.cancel:
			mChildAdapter.clearSelected();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.zxstudio.encrypt.task.EncryptListener.CallBack#notifyResult(java.
	 * util.List, java.util.List)
	 */
	@Override
	public void notifyResult(List<String> sucessedFiles,
			List<String> failedFiles) {
		for (String path : sucessedFiles) {
			Log.v(TAG, path + " 加密成功");
		}

		for (String path : failedFiles) {
			Log.v(TAG, path + " 加密失败");
		}
		mHandler.sendEmptyMessage(0);
	}

}
